import Keycloak from 'keycloak-js'

const _kc = new Keycloak({
  url: 'https://paas-auth.holderzone.cn',
  realm: 'paas',
  clientId: 'holder_mb'
})

const initKeycloak = (onAuthenticatedCallback: () => void) => {
  _kc
    .init({ onLoad: 'login-required' })
    .then((authenticated) => {
      if (!authenticated) {
        console.log('user is not authenticated..!')
      }
      setInterval(() => {
        if (_kc.isTokenExpired(13)) {
          _kc.updateToken(-1)
        }
      }, 1000 * 10)
      sessionStorage.setItem('access_token', _kc.token ?? '')
      onAuthenticatedCallback()
    })
    .catch(console.error)
}

const doLogin = _kc.login

const doLogout = _kc.logout

const getToken = () => _kc.token

const isLoggedIn = () => !!_kc.token

const updateToken = () =>
  _kc
    .updateToken(-1)
    .then((successCallback) => {
      sessionStorage.setItem('access_token', _kc.token ?? '')
    })
    .catch(doLogin)

const getUsername = () => _kc.tokenParsed?.preferred_username

const hasRole = (roles: any[]) => roles.some((role) => _kc.hasRealmRole(role))

const isTokenExpired = () => _kc.isTokenExpired()

const getServerUrl = () => _kc.authServerUrl

const getRealm = () => _kc.realm

const getUserInfo = () => _kc.tokenParsed

const KeycloakClient = {
  initKeycloak,
  doLogin,
  doLogout,
  isLoggedIn,
  getToken,
  updateToken,
  getUsername,
  hasRole,
  isTokenExpired,
  getServerUrl,
  getRealm,
  getUserInfo
}

export default KeycloakClient
